package ninja

import (
	"bufio"
	_ "embed"
	"fmt"
	"io"
)

type Ninja struct {
	reqv string // require version
	tplt string // template, rule define.
	dtar string // default target.

	/**/
	vbs []*Variable
	rus []*Rule
	bds []*Build
}

func NewNinja() *Ninja {
	var nj Ninja

	/**/
	nj.reqv = "1.2"
	nj.dtar = ""

	/**/
	return &nj
}

func (nj *Ninja) SetReqVersion(major uint, minor uint) {
	nj.reqv = fmt.Sprintf("%d.%d", major, minor)
}

func (nj *Ninja) SetDefault(tar string) {
	nj.dtar = tar
}

// template for rules define..
func (nj *Ninja) SetTemplate(tpls string) {
	nj.tplt = tpls
}

func (nj *Ninja) AddVariable(vb *Variable) {
	nj.vbs = append(nj.vbs, vb)
}

func (nj *Ninja) AddRule(ru *Rule) {
	nj.rus = append(nj.rus, ru)
}

func (nj *Ninja) AddBuild(bd *Build) {
	nj.bds = append(nj.bds, bd)
}

func (nj *Ninja) Dump(w io.Writer) {
	bw := bufio.NewWriter(w)

	bw.WriteString("\n")
	bw.WriteString("ninja_required_version = " + nj.reqv + "\n")
	bw.WriteString("\n")

	/**/
	if len(nj.vbs) > 0 {
		bw.WriteString("# This is Variables\n\n")
		for _, vb := range nj.vbs {
			bw.WriteString(vb.String())
		}
	}

	/**/
	bw.WriteString("include " + nj.tplt + "\n\n")

	/*
		bw.WriteString("\n\n")
		if len(nj.rus) > 0 {
			bw.WriteString("# This is Rules\n\n")
			for _, ru := range nj.rus {
				bw.WriteString(ru.String() + "\n")
			}
		}
	*/

	if len(nj.bds) > 0 {
		bw.WriteString("##### generated builds from default.vake #####\n\n")
		for _, bd := range nj.bds {
			bw.WriteString(bd.String() + "\n")
		}
	}

	/**/
	if len(nj.dtar) > 0 {
		bw.WriteString("default " + nj.dtar + "\n")
	}

	/**/
	bw.WriteString("\n\n")
	bw.Flush()
	return
}
